package backed.config;

import backed.interceptor.JwtInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private JwtInterceptor jwtInterceptor;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 使用项目相对路径，确保跨平台兼容性
        String projectPath = System.getProperty("user.dir");
        String uploadDir = projectPath + "/uploads/";
        
        // 确保路径分隔符正确，使用File.separator处理不同操作系统
        uploadDir = uploadDir.replace("/", java.io.File.separator);

        // 配置静态资源映射，将/uploads/**路径映射到本地文件系统
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:" + uploadDir);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/api/**")  // 拦截所有/api/**路径
                .excludePathPatterns(
                        "/api/user/login",      // 排除登录接口
                        "/api/user/register",   // 排除注册接口
                        "/swagger-ui/**",       // 排除Swagger UI
                        "/v3/api-docs/**",      // 排除API文档
                        "/uploads/**"           // 排除文件上传访问路径
                );
    }
}